package cn.sskxyz.mongodb.locks;

import java.util.Map;

import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.core.convert.MongoConverter;

import com.mongodb.client.MongoClient;

@Configuration
@ConfigurationProperties(prefix = "system.core.mongodb")
public class MongoLockConfiguration {

	private Map<String, MongoProperties> multi;

	private String lockdb;
	
	public Map<String, MongoProperties> getMulti() {
		return multi;
	}

	public void setMulti(Map<String, MongoProperties> multi) {
		this.multi = multi;
	}

	public String getLockdb() {
		return lockdb;
	}

	public void setLockdb(String lockdb) {
		this.lockdb = lockdb;
	}

	@Bean
	public MongoTemplate lockMongoTemplate(Map<String, MongoClient> mongoClientMap, MongoConverter mongoConverter) {
		MongoProperties properties = multi.get(lockdb);
		SimpleMongoClientDatabaseFactory lockFactory = new SimpleMongoClientDatabaseFactory(
				mongoClientMap.get(lockdb), properties.getMongoClientDatabase());
		return new MongoTemplate(lockFactory, mongoConverter);
	}
	
	@Bean
	@Primary
	public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDatabaseFactory, MongoConverter mongoConverter) {
		return new MongoTemplate(mongoDatabaseFactory, mongoConverter);
	}
}
